<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>购物车</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f5f5f5;
        }

        .cart-container {
            width: 80%;
            max-width: 800px;
            background-color: white;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border-radius: 4px;
            margin-top: 20px;
            padding: 20px;
        }

        .cart-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .cart-header img {
            width: 50px;
            height: 50px;
        }

        .cart-header h1 {
            margin: 0;
            font-size: 24px;
            color: #333;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            border: 1px solid #eee;
            padding: 12px;
            text-align: left;
        }

        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
        }

        tr:hover {
            background-color: #f8f9fa;
        }

        .total {
            text-align: right;
            font-size: 18px;
            margin-top: 20px;
        }

        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 5px;
            cursor: pointer;
            margin: 0 5px;
            transition: background-color 0.3s ease, transform 0.3s ease;
        }

        button:hover {
            background-color: #2980b9;
            transform: translateY(-2px);
        }
    </style>
</head>
<body>
    <%
        Boolean loggedIn = (Boolean) session.getAttribute("loggedIn");
        if (loggedIn == null || !loggedIn) {
            response.sendRedirect("login.jsp");
            return;
        }
    %>
    <div class="cart-container">
        <div class="cart-header">
            <h1>购物车</h1>
            <img src="shops/car.png" alt="购物车图标">
        </div>
        <table>
            <tr>
                <th>商品名称</th>
                <th>数量</th>
                <th>单价</th>
                <th>总价</th>
                <th>操作</th>
            </tr>
            <!-- 商品数据将通过JavaScript动态填充 -->
        </table>
        <div class="total">
            总计: ￥0.00
        </div>
        <button class="pay-order-btn" onclick="payOrder()">支付订单</button>
    </div>
    <script>
        window.onload = function() {
            loadCartItems();
        };

        function loadCartItems() {
            fetch('/untitled_war_exploded/getCar')
                .then(response => response.json())
                .then(data => {
                    renderCartItems(data);
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取购物车信息失败');
                });
        }

        function renderCartItems(items) {
            const table = document.querySelector('table');
            let total = 0;
            let rowsHtml = '';

            items.forEach(item => {
                total += item.totalPrice;
                rowsHtml += `
                    <tr>
                        <td>${item.shopName}</td>
                        <td><img src="${item.shopImageUrl}" alt="${item.shopName}" style="width:50px;height:50px;"></td>
                        <td>${item.unitPrice}</td>
                        <td style="display: flex; align-items: center; justify-content: center;">
                            <button onclick="updateQuantity(${item.shopId}, -1)">-</button>
                            <span id="quantity-${item.shopId}" style="margin: 0 10px;">${item.quantity}</span>
                            <button onclick="updateQuantity(${item.shopId}, 1)">+</button>
                        </td>
                        <td>${item.totalPrice}</td>
                    </tr>
                `;
            });

            table.innerHTML = `
                <tr>
                    <th>商品名称</th>
                    <th>图片</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>总价</th>
                </tr>
            ` + rowsHtml;
            document.querySelector('.total').textContent = `总计: ￥${total.toFixed(2)}`;
        }

        function updateQuantity(shopId, change) {
            const quantityElement = document.querySelector(`#quantity-${shopId}`);
            const currentQuantity = parseInt(quantityElement.textContent);

            if (change < 0 && currentQuantity <= 1) {
                alert('商品数量不能少于1');
                return;
            }

            const url = change > 0 ? '/untitled_war_exploded/addToCar' : '/untitled_war_exploded/updateCarQuantity';

            fetch(`${url}?shopId=${shopId}&change=${change}`, {
                method: 'GET'
            })
            .then(response => {
                if (response.ok) {
                    loadCartItems(); // Reload cart items
                } else {
                    alert('更新数量失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新数量时发生错误');
            });
            console.log('Current Quantity:', currentQuantity);
        }

        function payOrder() {
            const totalAmount = parseFloat(document.querySelector('.total').textContent.replace('总计: ￥', ''));
            const paymentTime = new Date().getTime();
            const userId = <%= session.getAttribute("userId") %>;

            const url = `/untitled_war_exploded/addOrder?paymentAmount=${totalAmount}&paymentTime=${paymentTime}&userId=${userId}`;

            fetch(url, {
                method: 'GET'
            })
            .then(response => {
                if (response.ok) {
                    alert('支付成功，订单已生成');
                    // 清空购物车逻辑可以在这里添加
                } else {
                    alert('支付失败，请重试');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('支付时发生错误');
            });
        }
    </script>
</body>
</html>
